<template>
  <div class="live-time">
    <div v-if="showDate" class="date">{{ formattedDate }}</div>
    <div class="time">{{ formattedTime }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";

const props = defineProps<{
  showDate?: boolean; // 是否显示日期
  format24?: boolean; // 是否使用 24 小时制
}>();

// 响应式时间数据
const now = ref<Date>(new Date());

// 更新时间函数
const updateTime = () => {
  now.value = new Date();
};

// 启动定时器每秒更新
onMounted(() => {
  setInterval(updateTime, 1000);
});

// 格式化日期
const formattedDate = computed(() => {
  const date = now.value;
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const weekDays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  const weekDay = weekDays[date.getDay()];
  return `${year}-${month}-${day} ${weekDay}`;
});

// 格式化时间
const formattedTime = computed(() => {
  const date = now.value;
  let hours = date.getHours();
  let minutes = String(date.getMinutes()).padStart(2, "0");
  let seconds = String(date.getSeconds()).padStart(2, "0");
  let period = "";

  if (!props.format24) {
    // 12小时制
    period = hours >= 12 ? "PM" : "AM";
    hours = hours % 12 || 12;
  }

  return `${String(hours).padStart(2, "0")}:${minutes}:${seconds} ${period}`;
});
</script>

<style scoped>
.live-time {
  font-family: monospace;
  text-align: center;
}
.date {
  margin-bottom: 4px;
  font-size: 20px;
}
.time {
  font-size: 25px;
  font-weight: bold;
}
</style>
